/**
 * 格式化工具
 */

/**
 * 格式化时间
 */
export function formatTime(timestamp: string | number, format: string = 'YYYY-MM-DD HH:mm:ss'): string {
  const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp)

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second)
}

/**
 * 格式化相对时间
 */
export function formatRelativeTime(timestamp: string | number): string {
  const now = Date.now()
  const time = typeof timestamp === 'string' ? new Date(timestamp).getTime() : timestamp
  const diff = now - time

  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day

  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return formatTime(time, 'YYYY-MM-DD')
  }
}

/**
 * 格式化距离
 */
export function formatDistance(distance: number): string {
  if (distance < 1000) {
    return `${Math.round(distance)}m`
  } else if (distance < 10000) {
    return `${(distance / 1000).toFixed(1)}km`
  } else {
    return `${Math.round(distance / 1000)}km`
  }
}

/**
 * 格式化价格
 */
export function formatPrice(price: number): string {
  return price.toFixed(2)
}

/**
 * 格式化手机号
 */
export function formatPhone(phone: string): string {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 格式化数字
 */
export function formatNumber(num: number): string {
  if (num < 1000) {
    return String(num)
  } else if (num < 10000) {
    return `${(num / 1000).toFixed(1)}k`
  } else {
    return `${(num / 10000).toFixed(1)}w`
  }
}
